package com.cx.mall.seckill.controller;

import com.cx.mall.common.model.order.OrderDetail;
import com.cx.mall.common.utils.ResponseVO;
import com.cx.mall.seckill.service.IBuyService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/seckill/buy")
public class BuyController {
    @Autowired
    private IBuyService buyService;
    @Autowired
    private RedissonClient redissonClient;
    @GetMapping("/dcount/{aid}/{sid}")
    public ResponseVO dcount(@PathVariable("aid") Integer activityId, @PathVariable("sid") String skuId) throws Exception {
        // 1 获取锁
        // 锁名称：确保你的锁名称在分布式系统中是唯一的，以避免不同实例间对同一资源的竞争条件
        String lockName = "seckill:lock:sku:" + activityId + skuId;
        RLock lock = redissonClient.getLock(lockName);
        // 2 加锁
        // 尝试获取锁，最多等待1000毫秒，上锁以后100毫秒自动解锁
        boolean isLocked = lock.tryLock(1000, 100, TimeUnit.MILLISECONDS);
        if (isLocked) {
            try {
                // 扣减库存
                buyService.dcount(activityId,skuId);
            } finally {
                lock.unlock();
            }
        }
        return ResponseVO.success();
    }
}
